# coding: utf-8
# @Author: cyl
# @File: 10反射.py
# @Time: 2024/07/21 09:52:03
"""
    反射: 程序可以访问、检测和修改它本身状态或行为的一种能力
        hasattr(object, name) 判断object对象中是否包含一个name字符串对应的方法或属性
        getattr(object, name, default=None)
        setattr(x, y, v)
        delattr(x, y)
    为什么使用反射
        可以事先定义好接口 接口只有在被完成后才会被真正执行 这实现了即插即用
"""


class BlackMedium:
    fe_true = 'Ugly'

    def __init__(self, name, address):
        self.name = name
        self.address = address

    def sell_house(self):
        print('{}正在卖房子'.format(self.name))

    def rent_house(self):
        print('{}正在租房子'.format(self.name))


b: BlackMedium = BlackMedium('c', '黄浦区')
print(b.__dict__)
print(hasattr(b, 'name'))
print(hasattr(b, 'address'))
print(hasattr(b, 'sell_house'))
print(hasattr(b, 'rent_house'))

print(getattr(b, 'name'))
print(getattr(b, 'address'))
print(getattr(b, 'sell_house'))
print(getattr(b, 'rent_house'))
print(getattr(b, 'None', '没有这个属性'))

setattr(b, 'name', 'update_c')
setattr(b, 'test', '给对象设置属性')
setattr(b, 'func', lambda x: x + 1)
setattr(b, 'func1', lambda self: self.name + 'sua_bi')
print(b.__dict__)
print('对象添加方法属性1: ', b.func(1))
print('对象添加方法属性2: ', b.func1(b))

delattr(b, 'test')
print(b.__dict__)
print(b.test)   # 报错
